package com.ruoyi.develop.goodsInvoice.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.finance.financeAr.service.IFinanceArService;
import com.ruoyi.develop.goodsCustomer.domain.GoodsCustomer;
import com.ruoyi.develop.goodsCustomer.service.IGoodsCustomerService;
import com.ruoyi.develop.goodsInvoiceApplyDetail.domain.GoodsInvoiceApplyDetail;
import com.ruoyi.develop.goodsInvoiceApplyDetail.service.impl.GoodsInvoiceApplyDetailServiceImpl;
import com.ruoyi.develop.goodsInvoiceDetail.domain.GoodsInvoiceDetail;
import com.ruoyi.develop.goodsInvoiceDetail.service.IGoodsInvoiceDetailService;
import com.ruoyi.develop.goodsInvoiceInfo.domain.GoodsInvoiceInfo;
import com.ruoyi.develop.goodsInvoiceInfo.service.IGoodsInvoiceInfoService;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.service.IGoodsSaleService;
import com.ruoyi.develop.payApply.domain.PayApply;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.service.impl.ProjectBaseInfoServiceImpl;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.goodsInvoice.domain.GoodsInvoice;
import com.ruoyi.develop.goodsInvoice.service.IGoodsInvoiceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 发票管理Controller
 *
 * @author qh
 * @date 2023-01-05
 */
@RestController
@RequestMapping("/goodsInvoice/goodsInvoice")
public class GoodsInvoiceController extends BaseController {
    @Autowired
    private IGoodsInvoiceService goodsInvoiceService;
    @Autowired
    private IGoodsSaleService goodsSaleService;
    @Autowired
    private ExportServiceImpl exportService;
    @Autowired
    private GoodsInvoiceApplyDetailServiceImpl goodsInvoiceApplyDetailService;
    @Autowired
    private ProjectBaseInfoServiceImpl projectBaseInfoService;
    @Autowired
    private IGoodsInvoiceInfoService goodsInvoiceInfoService;
    @Autowired
    private IGoodsInvoiceDetailService invoiceDetailService;
    @Autowired
    private IFinanceArService financeArService;
    @Autowired
    private IGoodsCustomerService goodsCustomerService;


    /**
     * 查询发票管理列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoice:query')")
    @GetMapping("/list")
    public TableDataInfo list(GoodsInvoice entity) {
        startPage();
        List<GoodsInvoice> list = goodsInvoiceService.selectList(entity);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoice:query')")
    @GetMapping("/listWhx")
    public TableDataInfo listWhx(GoodsInvoice entity) {
        startPage();
        List<GoodsInvoice> list = goodsInvoiceService.selectListWhx(entity);
        return getDataTable(list);
    }

    /**
     * 导出发票管理列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoice:export')")
    @Log(title = "发票管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GoodsInvoice entity) {
        List<GoodsInvoice> list = goodsInvoiceService.selectList(entity);
        ExcelUtil<GoodsInvoice> util = new ExcelUtil<GoodsInvoice>(GoodsInvoice.class);
        util.exportExcel(response, list, "发票管理数据");
    }

    @GetMapping("/listBatch/{ids}")
    public TableDataInfo listBatch(@PathVariable("ids") String[] ids) {
        List<GoodsSale> list = goodsSaleService.listBatch(ids);
        return getDataTable(list);
    }


    @Log(title = "开票申请信息导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportInvoice")
    public AjaxResult exportInvoiceApply(GoodsInvoice entity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        String date = DateUtils.getTime();//默认当天
        startPage();
        List<GoodsInvoice> list = goodsInvoiceService.selectList(entity);
        list.stream().forEach(e -> {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("saleDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getInvoiceDate()));
            map.put("status", DictUtils.getDictLabel("invoice_apply_status", e.getStatus()));
            map.put("fundCallback", DictUtils.getDictLabel("invoice_back_status", e.getFundCallback()));
            map.put("backDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getBackDate()));
            e.setParams(map);
        });
        params.put("list", list);
        params.put("date", date);
        String fileName = request.getParameter("fileName");
        if (StringUtils.isBlank(fileName)) {
            fileName = "开票记录.xlsx";
        }
        String templateName = "开票申请记录.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
        return null;
    }


    @PutMapping
    public AjaxResult addBatch(@Validated @RequestBody GoodsInvoice entity) {
        entity.setDrawerId(getUserId());
        entity.setDrawerName(getUsername());
        return goodsInvoiceService.insert(entity);
    }

    /**
     * 单个订单新增 付款申请
     */
    @PutMapping(value = "/singleAdd")
    public AjaxResult singleAdd(@Validated @RequestBody GoodsInvoice entity) {
        // 更新 订单上的开票金额
        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(entity.getProjectId());

        GoodsCustomer goodsCustomer =goodsCustomerService.selectById(entity.getCustomerId());
        if(goodsCustomer!=null){
            entity.setTaxNo(goodsCustomer.getTaxNo());
        }

        entity.setDrawerId(getUserId());
        entity.setDrawerName(getUsername());
        entity.setStatus(BusinessConstants.TAX_STATUS_0);
        entity.setProjectNo(projectBaseInfo.getCode());
        entity.setProjectId(projectBaseInfo.getId());
        entity.setFrameworkId(projectBaseInfo.getProjectId());
        entity.setFrameworkCode(projectBaseInfo.getProjectCode());
        goodsInvoiceService.insert(entity);
        // 插入 开票申请 明细
        GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
        goodsInvoiceApplyDetail.setApplyId(entity.getId());
        goodsInvoiceApplyDetail.setAmount(entity.getAmount());
        goodsInvoiceApplyDetail.setProjectId(entity.getProjectId());
        goodsInvoiceApplyDetail.setProjectNo(entity.getProjectNo());
        goodsInvoiceApplyDetailService.insert(goodsInvoiceApplyDetail);

        if (projectBaseInfo != null) {
            projectBaseInfo.setTaxRemain(projectBaseInfo.getTaxRemain().subtract(entity.getAmount()));
            System.out.println(projectBaseInfo.getTaxRemain());
            projectBaseInfoService.update(projectBaseInfo);
        }

        return AjaxResult.success("开票申请操作成功");
    }

    /**
     * 获取发票管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoice:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(goodsInvoiceService.selectById(id));
    }

    @GetMapping(value = "/getAllMoney/{ids}")
    public AjaxResult getAllMoney(@PathVariable("ids") String ids) {
        BigDecimal allMoney = BigDecimal.ZERO;
        for (String id : ids.split(",")) {
            allMoney = allMoney.add(goodsInvoiceService.selectById(id).getAmount());
        }
        return AjaxResult.success(allMoney);
    }

    /**
     * 新增发票管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoice:add')")
    @Log(title = "发票管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody GoodsInvoice entity) {
        return goodsInvoiceService.insert(entity);
    }

    /**
     * 修改发票管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoice:edit')")
    @Log(title = "发票管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody GoodsInvoice entity) {
        return toAjax(goodsInvoiceService.update(entity));
    }

    @PutMapping("/updateInvoice")
    @Log(title = "更新发票信息", businessType = BusinessType.UPDATE)
    public AjaxResult updateInvoice(@RequestBody GoodsInvoice entity) {
        return toAjax(goodsInvoiceService.update(entity));
    }

    /**
     * 删除发票管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoice:remove')")
    @Log(title = "发票管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        for (String id : ids) {
//            GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(id);
//            if (StringUtils.isNotEmpty(goodsInvoice.getSaleId())) {
//                for (String saleid : goodsInvoice.getSaleId().split(",")) {
//                    GoodsSale goodsSale = goodsSaleService.selectById(saleid);
//                    goodsSale.setInvoice(BusinessConstants.STATUS_NO);
//                    goodsSaleService.update(goodsSale);
//                }
//            }
            // 删除对应的开票明细
            GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
            goodsInvoiceApplyDetail.setApplyId(id);
            List<GoodsInvoiceApplyDetail> detailList = goodsInvoiceApplyDetailService.selectList(goodsInvoiceApplyDetail);
            if (detailList != null && !detailList.isEmpty()) {
                for (GoodsInvoiceApplyDetail detail : detailList) {
                    goodsInvoiceApplyDetailService.deleteById(detail.getId());
                    // 更新订单上的 项目金额
                    ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(detail.getProjectId());
                    if (projectBaseInfo != null) {
                        projectBaseInfo.setTaxRemain(projectBaseInfo.getTaxRemain().add(detail.getAmount()));
                        projectBaseInfoService.update(projectBaseInfo);
                    }
                }
            }
        }
        return toAjax(goodsInvoiceService.deleteByIds(ids));
    }

    //订单批量开票
    @PostMapping("/insertBatch")
    public AjaxResult insertBatch(@Validated @RequestBody GoodsInvoice entity) {
        goodsInvoiceService.insertBatch(entity);
        return AjaxResult.success("销售成功");
    }

    //订单合并开票
    @PostMapping("/insertBatchAll")
    public AjaxResult insertBatchAll(@Validated @RequestBody GoodsInvoice entity) {
        goodsInvoiceService.insertBatchAll(entity);
        return AjaxResult.success("销售成功");
    }


    /**
     * 开票
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoice:edit')")
    @Log(title = "开票", businessType = BusinessType.UPDATE)
    @PutMapping("/openInvoice")
    public AjaxResult openInvoice(@RequestBody GoodsInvoice entity) {
        // 更新订单开票金额

        if(BusinessConstants.TAX_STATUS_2.equals(entity.getStatus())){
            return  AjaxResult.error("开票失败，"+entity.getProjectNo()+":"+entity.getAmount()+"，该发票已经开票");
        }
        entity.setPinRemain(entity.getAmount());
        entity.setPinMoney(BigDecimal.ZERO);
        entity.setRemaining(BigDecimal.ZERO);
        entity.setStatus(BusinessConstants.TAX_STATUS_2);
        entity.setAmountReal(entity.getAmount());

        // 合并 开票 和不合并 开票
        GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
        goodsInvoiceApplyDetail.setApplyId(entity.getId());
        List<GoodsInvoiceApplyDetail> detailList = goodsInvoiceApplyDetailService.selectList(goodsInvoiceApplyDetail);
        if (detailList != null && !detailList.isEmpty()) {
            for (GoodsInvoiceApplyDetail detail : detailList) {
                // 更新订单上的 项目金额
                ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(detail.getProjectId());
                if (projectBaseInfo != null) {
                    projectBaseInfo.setTaxAll(projectBaseInfo.getTaxAll().add(detail.getAmount()));
                    if(projectBaseInfo.getTaxRemain().compareTo(BigDecimal.ZERO)==0){
                        projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_2);
                        projectBaseInfo.setInvoicingTime(new Date());
                    }
                    if(projectBaseInfo.getTaxRemain().compareTo(BigDecimal.ZERO) > 0){
                        projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_1);
                    }
                    if(projectBaseInfo.getTaxRemain().compareTo(projectBaseInfo.getTaxAll()) == 0){
                        projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_0);
                    }
                    projectBaseInfoService.update(projectBaseInfo);
                }
            }
        }
        return toAjax(goodsInvoiceService.update(entity));
    }

    /**
     * 批量开票
     */
    @GetMapping("/batchInvoice/{ids}/{invoiceDate}")
    @Transactional
    public AjaxResult batchInvoice(@PathVariable String[] ids, @PathVariable("invoiceDate") String invoiceDate) {
        // 先判断是否所有
        Date date = DateUtils.parseDate(invoiceDate);
        for (String id : ids) {
            GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(id);
            if(BusinessConstants.TAX_STATUS_2.equals(goodsInvoice.getStatus())){
                return  AjaxResult.error("开票失败，"+goodsInvoice.getProjectNo()+":"+goodsInvoice.getAmount()+"，该发票已经开票");
            }
            goodsInvoice.setInvoiceDate(new Date());
            goodsInvoice.setPinRemain(goodsInvoice.getAmount());
            goodsInvoice.setPinMoney(BigDecimal.ZERO);
            goodsInvoice.setStatus(BusinessConstants.TAX_STATUS_2);
            goodsInvoice.setRemaining(BigDecimal.ZERO);
            goodsInvoice.setAmountReal(goodsInvoice.getAmount());
            goodsInvoice.setInvoiceDate(date);
            goodsInvoiceService.update(goodsInvoice);
            GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
            goodsInvoiceApplyDetail.setApplyId(id);
            List<GoodsInvoiceApplyDetail> detailList = goodsInvoiceApplyDetailService.selectList(goodsInvoiceApplyDetail);
            if (detailList != null && !detailList.isEmpty()) {
                for (GoodsInvoiceApplyDetail detail : detailList) {
                    // 更新订单上的 项目金额
                    ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(detail.getProjectId());
                    if (projectBaseInfo != null) {
                        projectBaseInfo.setTaxAll(projectBaseInfo.getTaxAll().add(detail.getAmount()));
                        if(projectBaseInfo.getTaxRemain().compareTo(BigDecimal.ZERO)==0){
                            projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_2);
                            projectBaseInfo.setInvoicingTime(new Date());
                        }else if(projectBaseInfo.getTaxRemain().compareTo(projectBaseInfo.getContractMoney()) == 0){
                            projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_0);
                            projectBaseInfo.setInvoicingTime(null);
                        } else {
                            projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_1);
                            projectBaseInfo.setInvoicingTime(null);
                        }
                        projectBaseInfoService.update(projectBaseInfo);
                    }
                }
            }

        }
        return AjaxResult.success("开票成功");
    }

    /**
     * 取消开票（批量）
     */
    @GetMapping("/cancelInvoice/{ids}")
    @Transactional
    public AjaxResult cancelInvoice(@PathVariable String[] ids) {
        for (String id : ids) {
            GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(id);
            if(BusinessConstants.TAX_STATUS_0.equals(goodsInvoice.getStatus())){
                return  AjaxResult.error("开票失败，"+goodsInvoice.getProjectNo()+":"+goodsInvoice.getAmount()+"，该发票已经撤销开票");
            }
            goodsInvoice.setStatus(BusinessConstants.TAX_STATUS_0);
            goodsInvoice.setNo("");
            goodsInvoice.setInvoiceDate(null);
            goodsInvoice.setRemaining(goodsInvoice.getAmount());
            goodsInvoice.setAmountReal(BigDecimal.ZERO);
            goodsInvoiceService.update(goodsInvoice);
            GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
            goodsInvoiceApplyDetail.setApplyId(id);
            List<GoodsInvoiceApplyDetail> detailList = goodsInvoiceApplyDetailService.selectList(goodsInvoiceApplyDetail);
            if (detailList != null && !detailList.isEmpty()) {
                for (GoodsInvoiceApplyDetail detail : detailList) {
                    // 更新订单上的 项目金额
                    ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(detail.getProjectId());
                    if (projectBaseInfo != null) {
                        projectBaseInfo.setTaxAll(projectBaseInfo.getTaxAll().subtract(detail.getAmount()));
                        if(projectBaseInfo.getTaxAll().compareTo(BigDecimal.ZERO) == 0){
                            projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_0);

                        }else if(projectBaseInfo.getTaxAll().compareTo(projectBaseInfo.getContractMoney()) == 0){
                            projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_2);
                        }else{
                            projectBaseInfo.setTaxStatus(BusinessConstants.TAX_STATUS_1);
                        }
                        projectBaseInfo.setInvoicingTime(null);
                        projectBaseInfoService.update(projectBaseInfo);
                    }
                }
            }
        }
        return AjaxResult.success("撤销开票成功");
    }


    /**
     * 发票核销
     */
    @PutMapping("/hexiao")
    @Transactional
    public AjaxResult hexiao(@RequestBody GoodsInvoice entity) {
        // 已核销
        entity.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
        // 合并 开票 和不合并 开票
        GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
        goodsInvoiceApplyDetail.setApplyId(entity.getId());
        List<GoodsInvoiceApplyDetail> detailList = goodsInvoiceApplyDetailService.selectList(goodsInvoiceApplyDetail);
        if (detailList != null && !detailList.isEmpty()) {
            for (GoodsInvoiceApplyDetail detail : detailList) {
                // 更新订单上的 回款金额
                ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(detail.getProjectId());
                if (projectBaseInfo != null) {
                    projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().add(detail.getAmount()));
                    projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().subtract(detail.getAmount()));
                    if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) == 0) {
                        projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
                        projectBaseInfo.setEndDate(new Date());
                    }
                    if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
                        projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
                    }
                    if (projectBaseInfo.getRemainMoney().compareTo(projectBaseInfo.getContractMoney()) == 0) {
                        projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_WHX);
                    }
                    projectBaseInfoService.update(projectBaseInfo);
                }
            }
        }
        return toAjax(goodsInvoiceService.update(entity));
    }


    /**
     * 批量核销
     */
    @GetMapping("/batchHexiao/{ids}")
    @Transactional
    public AjaxResult batchHexiao(@PathVariable String[] ids) {
        for (String id : ids) {

            GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(id);
            goodsInvoice.setBackDate(new Date());
            goodsInvoice.setPinRemain(goodsInvoice.getPinRemain().subtract(goodsInvoice.getAmount()));
            goodsInvoice.setPinMoney(goodsInvoice.getPinMoney().add(goodsInvoice.getAmount()));
            // 判断是否核销完成
            if (goodsInvoice.getPinMoney().compareTo(goodsInvoice.getAmount()) == 0) {
                goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
            }
            if(goodsInvoice.getPinMoney().compareTo(goodsInvoice.getAmount()) < 0){
                goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
            }
            goodsInvoiceService.update(goodsInvoice);
            // 插入 核销记录
            GoodsInvoiceDetail invoiceDetail = new GoodsInvoiceDetail();
            invoiceDetail.setInvoiceId(id);
            invoiceDetail.setPinDate(new Date());
            invoiceDetail.setPinMoney(goodsInvoice.getAmount());
            invoiceDetail.setProjectId(goodsInvoice.getProjectId());
            invoiceDetail.setProjectNo(goodsInvoice.getProjectNo());
            invoiceDetail.setCustomerId(goodsInvoice.getCustomerId());
            invoiceDetail.setCustomerName(goodsInvoice.getCustomerName());
            invoiceDetailService.insert(invoiceDetail);

            financeArService.addByBackMoney(invoiceDetail);

            GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
            goodsInvoiceApplyDetail.setApplyId(id);
            List<GoodsInvoiceApplyDetail> detailList = goodsInvoiceApplyDetailService.selectList(goodsInvoiceApplyDetail);
            if (detailList != null && !detailList.isEmpty()) {
                for (GoodsInvoiceApplyDetail detail : detailList) {
                    // 更新订单上的 回款金额
                    ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(detail.getProjectId());
                    if (projectBaseInfo != null) {
                        projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().add(detail.getAmount()));
                        projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().subtract(detail.getAmount()));
                        if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) == 0) {
                            projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
                        }
                        if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
                            projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
                        }
                        if (projectBaseInfo.getRemainMoney().compareTo(projectBaseInfo.getContractMoney()) == 0) {
                            projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);

                        }
                        projectBaseInfoService.update(projectBaseInfo);
                    }
                }
            }

        }
        return AjaxResult.success("批量核销成功");
    }



    /**
     * 取消核销
     */
    @GetMapping("/cancelHexiao/{ids}")
    public AjaxResult cancelHexiao(@PathVariable String[] ids) {
        for (String id : ids) {
            GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(id);
            goodsInvoice.setBackDate(null);
            goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_WHX);
            goodsInvoiceService.update(goodsInvoice);

            GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
            goodsInvoiceApplyDetail.setApplyId(id);
            List<GoodsInvoiceApplyDetail> detailList = goodsInvoiceApplyDetailService.selectList(goodsInvoiceApplyDetail);
            if (detailList != null && !detailList.isEmpty()) {
                for (GoodsInvoiceApplyDetail detail : detailList) {
                    // 更新订单上的 回款金额
                    ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(detail.getProjectId());
                    if (projectBaseInfo != null) {
                        projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().subtract(detail.getAmount()));
                        projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().add(detail.getAmount()));
                        if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) == 0) {
                            projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
                        }
                        if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
                            projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
                        }
                        if (projectBaseInfo.getRemainMoney().compareTo(projectBaseInfo.getContractMoney()) == 0) {
                            projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
                        }
                        projectBaseInfo.setEndDate(null);
                        projectBaseInfoService.update(projectBaseInfo);
                    }
                }
            }

        }
        return AjaxResult.success("批量取消核销成功");
    }







}
